<?php

chdir("../../");
require 'runtime.php';
require_once dirname(__FILE__). '/defined.php';
global $weechat_config;

define ( "TOKEN", $weechat_config["token"] );

$wechatObj = new wechatCallbackApi ();
//$wechatObj->valid();		// 申请修改服务器提交URL时才需要
$wechatObj->responseMsg();

class wechatCallbackApi {
	
	public function valid(){
        $echoStr = $_GET["echostr"];

        //valid signature , option
        if($this->checkSignature()){
        	echo $echoStr;
        	exit;
        }
    }
    
    public function save_record($postObj){
    	$db = init_db();
		$db->startTrans();
		$row = $db->get_row("select id from chat_user where user='" . $postObj->FromUserName . "'");
		if(false===$row){
			$db->query("insert into chat_user(source,user) values('wechat', '". $postObj->FromUserName. "')");
			$uid = $db->insert_id();
		}else{
			$uid = $row["id"];
		}
		$db->query("insert into chat_record(uid,FromUserName,MsgType,Content,data) values(
				{$uid}, '" . $postObj->FromUserName . "','" . $postObj->MsgType . "',
				'" . $postObj->Content . "','" . serialize(xml2array($postObj)) . "')");
    	$db->commit();
    	$db = null;
    }
	
	public function responseMsg() {
		// get post data, May be due to the different environments
		if(!isset($GLOBALS["HTTP_RAW_POST_DATA"])) exit("");
		$postStr = $GLOBALS ["HTTP_RAW_POST_DATA"];
		
		// extract post data
		if (! empty ( $postStr )) {
			
			$postObj = simplexml_load_string ( $postStr, 'SimpleXMLElement', LIBXML_NOCDATA );
			$this->save_record($postObj);	// 记录
			$msgType = $postObj->MsgType;
			$action = "receive_{$msgType}";
			$action_file = dirname(__FILE__). "/action/{$action}.php";
			if(file_exists($action_file)){
				$func = require $action_file;
				$func($postObj);
				
			}else{
				
				reply_text_msg($postObj, $action);

			}
			
		} else {
			exit ("");
		}
	}
	
	/**
	 * 验证消息真实性
	 * @param string $signature
	 * @param timestamp $timestamp
	 * @param int $nonce
	 * @return boolean
	 */
	private function checkSignature() {
		$signature = filter_input(INPUT_GET, "signature");
		$timestamp = filter_input(INPUT_GET, "timestamp", FILTER_SANITIZE_NUMBER_INT);
		$nonce = filter_input(INPUT_GET, "nonce", FILTER_SANITIZE_NUMBER_INT);
		
		$token = TOKEN;
		$tmpArr = array (
				$token,
				$timestamp,
				$nonce 
		);
		sort ( $tmpArr, SORT_STRING );
		$tmpStr = implode ( $tmpArr );
		$tmpStr = sha1 ( $tmpStr );
		
		if ($tmpStr == $signature) {
			return true;
		} else {
			return false;
		}
	}
}




/**
 * 发送全局帮助信息
 * @param object $postObj
 */
function reply_help_msg($postObj){
	$text = "另类天气扩展：用你的手机、平板、电脑等日历程序显示天气、节假日、农历等提醒。绿色环保，不安装第三方软件，定制方便灵活，兼容所有手机和电脑操作系统！\n\n";
	$text .= "天气定制功能请进入下方的天气订阅菜单查询详细和使用方法。\n\n";
	$text .= "天气查询格式：\n城市+天气\n城市+明天天气\n城市+后天天气\n如果不填写城市表示为当前所在的城市。";
	reply_text_msg($postObj, $text);
}

/**
 * 获取天气信息
 * @param string $city
 * @param int $weather_day 0：今天，1明天，2后天
 */
function get_weather($city, $weather_day=0){
	$day_data = array("今天", "明天", "后天");

	// 将城市名称转换成城市ID
	require 'library/defined.cityid.php';
	// 提取城市天气
	$cityid = $CITYID[Pinyin($city)];
	if(!strlen($cityid)) return "获取天气失败！";
	
	$url = "http://w.mdeve.com/{$cityid}.xml";
	$opts = array( 'http'=>array( 'method'=>"GET", 'timeout'=>60, ) );
	$context = stream_context_create($opts);
	$data =file_get_contents($url, false, $context);
	$xml = simplexml_load_string($data);
	$data = xml2array($xml);

	$s = ($data["city_1"]=="城区" ? $data["city_2"] : $data["city_1"]) . $day_data[$weather_day] . "天气预报：";
	if($weather_day == 0){
		$s .= $data["today"]["title_1"].$data["today"]["weather_1"]."，". $data["today"]["wind_direction_1"].$data["today"]["wind_power_1"]. "；"; 
		$s .= $data["today"]["title_2"].$data["today"]["weather_2"]."，". $data["today"]["wind_direction_2"].$data["today"]["wind_power_2"]. "；";
		$s .= "温度：". $data["today"]["temperature_1"]. "℃~". $data["today"]["temperature_2"]. "℃。";
		$s .=  "更详细的信息请订阅本站提供的天气、节日、农历信息。";
	}elseif($weather_day == 1){
		$s .= "明天白天".$data["tomorrow"]["weather_day"]."，". $data["tomorrow"]["wind_direction_day"].$data["tomorrow"]["wind_power_day"]. "；"; 
		$s .= "明天晚上".$data["tomorrow"]["weather_night"]."，". $data["tomorrow"]["wind_direction_night"].$data["tomorrow"]["wind_power_night"]. "；";
		$s .= "温度：". $data["tomorrow"]["temperature_day"]. "℃~". $data["tomorrow"]["temperature_night"]. "℃。";
		$s .=  "更详细的信息请订阅本站提供的天气、节日、农历信息。";
	}elseif($weather_day == 2){
		$s .= "后天白天".$data["after_tomorrow"]["weather_day"]."，". $data["after_tomorrow"]["wind_direction_day"].$data["after_tomorrow"]["wind_power_day"]. "；";
		$s .= "后天晚上".$data["after_tomorrow"]["weather_night"]."，". $data["after_tomorrow"]["wind_direction_night"].$data["after_tomorrow"]["wind_power_night"]. "；";
		$s .= "温度：". $data["after_tomorrow"]["temperature_day"]. "℃~". $data["after_tomorrow"]["temperature_night"]. "℃。";
		$s .=  "更详细的信息请订阅本站提供的天气、节日、农历信息。";
	}else{
		$s = "获取天气错误！";
	}
	return $s;
}


/**
 * 发送被动响应消息
 * @param string $fromUsername
 * @param string $toUsername
 * @param string $content 回复内容
 */
function reply_text_msg($postObj, $content){
	
	$fromUsername = $postObj->FromUserName;
	$toUsername = $postObj->ToUserName;
	$createTime = time();
	$msgType = "text";
	$textTpl = "<xml>
							<ToUserName><![CDATA[%s]]></ToUserName>
							<FromUserName><![CDATA[%s]]></FromUserName>
							<CreateTime>%s</CreateTime>
							<MsgType><![CDATA[%s]]></MsgType>
							<Content><![CDATA[%s]]></Content>
							<FuncFlag>0</FuncFlag>
							</xml>";
	$time = time ();
	$msgType = "text";
	$contentStr = $content;
	$resultStr = sprintf ( $textTpl, $fromUsername, $toUsername, $time, $msgType, $contentStr );
	echo $resultStr;
	exit;
}

?>